package com.hmall.search.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.api.dto.ItemDTO;
import com.hmall.item.domain.query.ItemPageQuery;
import com.hmall.common.domain.PageDTO;
import com.hmall.common.utils.BeanUtils;
import com.hmall.common.utils.CollUtils;
import com.hmall.item.domain.po.ItemDoc;
import com.hmall.search.service.ISearchService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 李建舜
 * @version 1.0
 * @date 2025/3/15 15:26
 * @description
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SearchServiceImpl implements ISearchService {
    private final RestHighLevelClient client;

    @Override
    public ItemDTO queryItemById(Long id) throws IOException {
        log.info("使用ElasticSearch根据id查询商品");
        // 1.创建Request
        GetRequest getRequest = new GetRequest("items", id.toString());
        // 2.发送请求
        GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
        // 3.解析响应
        if (!response.isExists()) {
            return null;
        }
        String sourceAsString = response.getSourceAsString();
        ItemDoc bean = JSONUtil.toBean(sourceAsString, ItemDoc.class);
        return BeanUtils.copyBean(bean, ItemDTO.class);
    }

    @Override
    public PageDTO<ItemDTO> search(ItemPageQuery query) throws IOException {
        // 1. 准备查询条件
        SearchRequest request = new SearchRequest("items");
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StrUtil.isNotBlank(query.getKey())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", query.getKey()));
        }
        if (StrUtil.isNotBlank(query.getBrand())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("brand", query.getBrand()));
        }
        if (StrUtil.isNotBlank(query.getCategory())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("category", query.getCategory()));
        }
        if (query.getMinPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(query.getMinPrice()));
        }
        if (query.getMaxPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").lte(query.getMaxPrice()));
        }

        // 分页设置
        request.source().from((query.getPageNo() - 1) * query.getPageSize()).size(query.getPageSize());

        // 排序设置
        if (StrUtil.isNotBlank(query.getSortBy())) {
            if (query.getIsAsc()) {
                request.source().sort(query.getSortBy(), SortOrder.ASC);
            } else {
                request.source().sort(query.getSortBy(), SortOrder.DESC);
            }
        }

        /*// 高亮显示
        request.source().highlighter(
                SearchSourceBuilder.highlight()
                        .field("key")
                        .preTags("<em>")
                        .postTags("</em>")
        );*/


        request.source().query(boolQueryBuilder);

        // 2. 发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);

        // 3. 解析响应结果
        List<ItemDTO> list = handleResponse(response);
        long total = response.getHits().getTotalHits().value;
        return new PageDTO<ItemDTO>(total, (long) query.getPageNo(), list);
//        PageDTO<ItemDTO> itemDTOPageDTO = new PageDTO<>();
//        ArrayList<ItemDTO> itemDTOS = new ArrayList<>();
//        // 3.1 解析结果
//        SearchHits searchHits = response.getHits();
//        // 3.2 查询总量
//        itemDTOPageDTO.setTotal(searchHits.getTotalHits().value);
//        // 3.3 查询的结果数组
//        SearchHit[] hits = searchHits.getHits();
//        for (SearchHit hit : hits) {
//            ItemDTO itemDTO = JSONUtil.toBean(hit.getSourceAsString(), ItemDTO.class);
//            itemDTOS.add(itemDTO);
//        }
//        itemDTOPageDTO.setList(itemDTOS);
//
//        // 4. 返回结果
//        return itemDTOPageDTO;
    }


    private List<ItemDTO> handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        // 1.获取总条数
//        long total = searchHits.getTotalHits().value;
//        System.out.println("共搜索到" + total + "条数据");
        // 2.遍历结果数组
        SearchHit[] hits = searchHits.getHits();
        List<ItemDTO> list = CollUtils.newArrayList();

        for (SearchHit hit : hits) {
            // 3.得到_source，也就是原始json文档
            String source = hit.getSourceAsString();
            // 4.反序列化并打印
            ItemDoc item = JSONUtil.toBean(source, ItemDoc.class);
            list.add(BeanUtils.copyBean(item, ItemDTO.class));
        }
        return list;
    }


    @Override
    public Map searchFilters(ItemPageQuery query) throws IOException {
        log.info("使用ElasticSearch搜索商品分类");
        SearchRequest searchRequest = new SearchRequest("items");

        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if (StrUtil.isNotBlank(query.getKey())) {
            queryBuilder.must(QueryBuilders.matchQuery("name", query.getKey()));
        }
        if (StrUtil.isNotBlank(query.getBrand())) {
            queryBuilder.filter(QueryBuilders.termQuery("brand", query.getBrand()));
        }
        if (StrUtil.isNotBlank(query.getCategory())) {
            queryBuilder.filter(QueryBuilders.matchQuery("category", query.getCategory()));
        }
        if (query.getMaxPrice() != null) {
            queryBuilder.filter(QueryBuilders.rangeQuery("price").gte(query.getMinPrice()).lte(query.getMaxPrice()));
        }

        String categoryAgg = "category_agg";
        String brandAgg = "brand_agg";
        searchRequest.source().query(queryBuilder).aggregation(
                        AggregationBuilders.terms(categoryAgg).field("category"))
                .aggregation(AggregationBuilders.terms(brandAgg).field("brand"));

        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);

        HashMap<String, List<String>> resultMap = new HashMap<>();
        Terms terms = response.getAggregations().get(categoryAgg);
        if (terms != null) {
            resultMap.put("category", terms.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList()));
        }
        terms = response.getAggregations().get(brandAgg);
        if (terms != null) {
            resultMap.put("brand", terms.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList()));
        }
        // 封装并返回
        return resultMap;
    }
}
